package javaTest04.exercise02.processor;

import javaTest03.exercise02.JdbcUtils;
import javaTest04.util.SqlUtils;

import java.sql.*;

public class PersonPersistence implements ObjectPersistenceAction {

    @Override
    public boolean process(Class<?> clazz, DBOperation operation) {

        if (!SqlUtils.isEntity(clazz))//该类是否为Entity
            return false;

        PreparedStatement statement = null;//sql操作对象
        Connection connection = null;//数据库连接对象
        ResultSet resultSet = null;

        try {
            connection = JdbcUtils.getConnection("javaTest04/resource/config");
            String sql = null;



            switch (operation) {//判断操作类型
                case CREATE:
                    sql = SqlUtils.generateCreateTableSql(clazz);
                    break;
                case DROP:
                    sql = SqlUtils.generateDeleteTableSql(clazz);
                    break;
                case ALTER:
                    sql = SqlUtils.generateAlterTableSql(clazz);
                    break;
                case DESC:
                    sql = SqlUtils.generateDescTableSql(clazz);
                    break;
            }

            statement = connection.prepareStatement(sql);

            statement.execute(sql);

            System.out.println("操作" + operation.name() + "执行成功");

            return true;
        } catch (SQLException e) {
            System.out.println("操作" + operation.name() + "执行失败");
            throw new RuntimeException(e);
        } finally {
            JdbcUtils.closeConnection(connection, statement, resultSet);
        }
    }
}
